package cn.ulyer.core.data;

import cn.hutool.core.util.StrUtil;
import cn.ulyer.common.constants.StatusEnum;
import cn.ulyer.common.jpa.entity.Dict;
import cn.ulyer.common.jpa.entity.DictItem;
import cn.ulyer.common.jpa.entity.QDict;
import cn.ulyer.common.jpa.entity.QDictItem;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;


/**
 * 字典数据服务
 */
@Service
@Slf4j
public class DictDataService {


    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    final static String DICT_PREFIX = "dict:";

    @PostConstruct
    public void initDict() {
        log.info("init system dict data");
        //初始化字典数据 redis 存储
        QDict qDict = QDict.dict;
        QDictItem dictItem = QDictItem.dictItem;
        List<Dict> dicts = jpaQueryFactory.selectFrom(qDict).where(qDict.status.eq(StatusEnum.ENABLE.status())).fetch();
        if (dicts != null) {
            dicts.forEach(dct -> {
                List<DictItem> dictItems = jpaQueryFactory.selectFrom(dictItem).where(
                        dictItem.dictId.eq(dct.getDictId()),
                        dictItem.status.eq(StatusEnum.ENABLE.status())
                ).fetch();
                for (DictItem item : dictItems) {
                    //模块:property
                    redisTemplate.opsForHash().put(DICT_PREFIX + dct.getModule() +":"+dct.getProperty(), item.getDictKey(), item);
                }
            });
        }
        log.info("system dict data init end");
    }


    /**
     * input value  output translation name
     *
     * @param module
     * @param key
     * @return
     */
    public String getValue(String module, String property, String key) {
        DictItem dictItem = (DictItem) redisTemplate.opsForHash().get(DICT_PREFIX + module + property, key);
        return dictItem == null ? key : dictItem.getDictValue();
    }

    public String getValue(String property, String key) {
        String module = getModule(property);
        return StrUtil.isBlank(module) ? null : getValue(module, property, key);
    }


    public String getModule(String property) {
        Dict dict = fetchFirst(property);
        return dict == null ? null : dict.getModule();
    }


    public Dict fetchFirst(String property) {
        QDict qDict = QDict.dict;
        return jpaQueryFactory.selectFrom(qDict).where(qDict.property.eq(property)).fetchFirst();
    }

}
